using AutoMapper;
using Domain;
using ErrorCode;
using Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using RabbitTraceability.Api.Applications.Command;
using RabbitTraceability.Api.Dtos.Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace RabbitTraceability.Api.Applications.CommandHandler
{
    /// <summary>
    /// 溯源信息查询命令处理器
    /// </summary>
    public class QueryTraceabilityInfoCommandHandler : IRequestHandler<QueryTraceabilityInfoCommand, ApiPaging<TraceabilityInfoDto>>
    {
        private readonly IRepository<TraceabilityInfo> _traceabilityRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<QueryTraceabilityInfoCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="traceabilityRepository">溯源信息仓储</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        public QueryTraceabilityInfoCommandHandler(
            IRepository<TraceabilityInfo> traceabilityRepository,
            IMapper mapper,
            ILogger<QueryTraceabilityInfoCommandHandler> logger)
        {
            _traceabilityRepository = traceabilityRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理查询请求
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页结果</returns>
        public async Task<ApiPaging<TraceabilityInfoDto>> Handle(QueryTraceabilityInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询溯源信息，页码：{PageIndex}，每页记录数：{PageSize}", request.PageIndex, request.PageSize);

                // 验证分页参数
                if (request.PageIndex < 1)
                {
                    request.PageIndex = 1;
                }

                if (request.PageSize < 1 || request.PageSize > 100)
                {
                    request.PageSize = 10;
                }

                // 构建查询条件
                var query = _traceabilityRepository.GetAll().AsNoTracking().Where(x=>x.IsDeleted==false);

                // 应用查询条件（所有条件均可为空）
                if (!string.IsNullOrWhiteSpace(request.ProductName))
                {
                    query = query.Where(t => t.ProductName.Contains(request.ProductName));
                }

                if (!string.IsNullOrWhiteSpace(request.ProductionBatch))
                {
                    query = query.Where(t => t.ProductionBatch == request.ProductionBatch);
                }

                if (!string.IsNullOrWhiteSpace(request.ShelfLife))
                {
                    query = query.Where(t => t.ShelfLife == request.ShelfLife);
                }

                if (!string.IsNullOrWhiteSpace(request.ProductionLicense))
                {
                    query = query.Where(t => t.ProductionLicense == request.ProductionLicense);
                }

                if (!string.IsNullOrWhiteSpace(request.Manufacturer))
                {
                    query = query.Where(t => t.Manufacturer.Contains(request.Manufacturer));
                }

                if (!string.IsNullOrWhiteSpace(request.CreatedBy))
                {
                    query = query.Where(t => t.CreatedBy != null && t.CreatedBy.Contains(request.CreatedBy));
                }

                if (request.CreatedTime.HasValue)
                {
                    var startDate = request.CreatedTime.Value.Date;
                    var endDate = startDate.AddDays(1).AddTicks(-1);
                    query = query.Where(t => t.CreatedTime != null && t.CreatedTime >= startDate && t.CreatedTime <= endDate);
                }

                if (!string.IsNullOrWhiteSpace(request.LastModifiedBy))
                {
                    query = query.Where(t => t.LastModifiedBy != null && t.LastModifiedBy.Contains(request.LastModifiedBy));
                }

                if (request.LastModifiedTime.HasValue)
                {
                    var startDate = request.LastModifiedTime.Value.Date;
                    var endDate = startDate.AddDays(1).AddTicks(-1);
                    query = query.Where(t => t.LastModifiedTime.HasValue && t.LastModifiedTime >= startDate && t.LastModifiedTime <= endDate);
                }

                // 默认按创建时间倒序排序
                query = query.OrderByDescending(t => t.CreatedTime);

                // 计算总记录数
                var totalCount = await query.CountAsync(cancellationToken);

                // 执行分页查询
                var items = await query
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 映射为DTO
                var dtoItems = _mapper.Map<List<TraceabilityInfoDto>>(items);

                _logger.LogInformation("溯源信息查询完成，总记录数：{TotalCount}", totalCount);

                // 返回分页结果
                return new ApiPaging<TraceabilityInfoDto>
                {
                    PageIndex = request.PageIndex,
                    PageSize = request.PageSize,
                    TotalCount = totalCount,
                    TotalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize),
                    Data = dtoItems
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询溯源信息时发生错误: {Message}", ex.Message);
                throw new ApiException(ResultCode.服务器错误, "查询溯源信息失败，请稍后再试");
            }
        }
    }
} 